/**
 * promise封装ajax异步任务
 * @param {*} options 
 */
function myAjaxPromise(options){
   return new Promise(function(resolve,reject){
        myajax({
            method: options.method,
            url:options.url,
            data: options.data,
            success: function(result){
                resolve(result)
            },
            error:function(err){
                reject(err)
            }
        })
    })
}


function myajax(options) {
    //1. 获取XMLHttpRequest
    const xhr = new window.XMLHttpRequest()
    //格式化参数
    let parms = formatParma(options.data)
    if (options.method.toUpperCase() == 'GET') {
        //2. 建立连接
        xhr.open(options.method, options.url + '?' + parms) //http://ip:port/login?username='admin'&age=21
        xhr.send()
    } else if (options.method.toUpperCase() == 'POST') {
        xhr.open(options.method, options.url)
        //3.发送请求
        //设置传输的参数数据类型content-type, 支持名称1=值1&名称2=值2
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(parms)
    }

    //4.处理响应数据
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                let result = xhr.responseText
                result = JSON.parse(result) //json字符串转json对象
                options.success(result)
            } else {
                options.error(xhr.status + xhr.statusText)
            }
        }
    }
}

/**
 let obj=  {
     username:'admin',
     age:21,            =>   `username='admin' & age=21& headerimg="http://222.jpg"
     headrimg:''
   }  
   遍历对象
      for(let key in obj){
         // key, obj[key]
      }
 */
function formatParma(obj) {
    let arr = []
    for (let key in obj) {
        let item = `${key}=${obj[key]}` //username='admin'
        arr.push(item) //[username='admin', age=21,headerimg="http://222.jpg"]
    }
    let str = arr.join('&') //`username='admin' & age=21& headerimg="http://222.jpg"
    return str
}